//
//  WmcCombinePhotoFeedbackAlertView.swift
//  YPWatermarkCamera
//
//  Created by Json on 2023/8/1.
//

import UIKit
import RxSwift
import YYText

class WmcCombinePhotoFeedbackAlertView: WmcBaseView, WmcAlertViewProtocol {
    /// 标题控件
    private lazy var titleView: WmcCPFeedbackTitleView = {
        let view = WmcCPFeedbackTitleView()
        view.title = "更多功能"
        return view
    }()
    
    private lazy var stackView: UIStackView = {
        let stackV = UIStackView()
        stackV.axis = .vertical
        stackV.spacing = 16.0.wmc_autoHor
        stackV.distribution = .fill
        stackV.alignment = .fill
        return stackV
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = 17.wmc_scaleFont()
        label.textColor = UIColor.wmc_black85
        label.text = "请告诉我们，您需要什么功能？"
        return label
    }()
    
    private lazy var itemsView: UIStackView = {
        let stackV = UIStackView()
        stackV.axis = .vertical
        stackV.spacing = 20.0.wmc_autoHor
        stackV.distribution = .fill
        stackV.alignment = .fill
        return stackV
    }()
    
    private lazy var textView: WmcPlaceholderTextView = {
        let view = WmcPlaceholderTextView()
        view.backgroundColor = UIColor.wmc_gray_F7F8FA
        view.font = 13.wmc_scaleFont()
        view.textColor = UIColor.wmc_black85
        let maxCount = 50
        view.placeholderLabel.text = "请输入需要的其他功能（\(maxCount)字以内）"
        view.limitedNumber = maxCount
        view.layer.cornerRadius = 4.0
        view.clipsToBounds = true
        // 默认隐藏
        view.isHidden = true
        return view
    }()
    
    private lazy var submitButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.wmc_mainTheme
        button.setTitle("提交", for: .normal)
        button.setTitleColor(UIColor.wmc_white_FFFFFF, for: .normal)
        button.titleLabel?.font = 17.wmc_scaleFont(weight: .medium)
        button.layer.cornerRadius = 6.0
        button.clipsToBounds = true
        return button
    }()
    
    private lazy var tipLabel: YYLabel = {
        let label = YYLabel()
        label.numberOfLines = 0
        let join = "点击加群"
        let text = "加入产品共创群，与我们直接沟通  \(join)"
        let range = (text as NSString).range(of: join)
        let attrText = text.yp.makeAttributed { make in
            make.set(font: 13.wmc_scaleFont())
            make.set(foregroundColor: UIColor.wmc_black65)
            make.set(font: 13.wmc_scaleFont(weight: .medium), range: range)
        }
        attrText.yy_setTextHighlight(range, color: UIColor.wmc_mainTheme, backgroundColor: nil) { [weak self] _, _, _, _ in
            guard let self = self else { return }
            self.handleJoinGroup()
        }
        label.attributedText = attrText
        label.textAlignment = .center
        return label
    }()
    
    var items: [WmcFeedbackItem] = [] {
        didSet {
            itemsView.yp.removeAllSubviews()
            items.forEach { item in
                let itemView = WmcCPFeedbackItemView()
                itemView.item = item
                itemsView.addArrangedSubview(itemView)
                itemView.snp.makeConstraints { make in
                    make.height.equalTo(24.0.wmc_autoHor)
                }
                itemView.rx.tapGesture().when(.recognized).subscribe(onNext: {
                    [weak self] _ in
                    guard let self = self else { return }
                    self.didSelected(itemView: itemView, item: item)
                }).disposed(by: rx.disposeBag)
            }
        }
    }
    
    var selectedItem: WmcFeedbackItem?
    
    static let disposeBag: DisposeBag = .init()
    
    private static let appId: Int = 101
    private static var configId: Int {
        return YPWmcManager.shared.environmentType.feedbackConfigId
    }
    
    // MARK: UI
    override func makeUI() {
        super.makeUI()
        let hMargin = 16.0.wmc_autoHor
        let vMargin = 16.0.wmc_autoHor
        layer.cornerRadius = 12.0
        layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        clipsToBounds = true
        // titleView
        addSubview(titleView)
        titleView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(48.0.wmc_autoHor)
        }
        // stackView
        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.top.equalTo(titleView.snp.bottom).offset(vMargin)
            make.left.equalTo(hMargin)
            make.right.equalTo(-hMargin)
            make.bottom.equalTo(-Wmc_safeAreaBottom-vMargin)
        }
        // titleLabel
        stackView.addArrangedSubview(titleLabel)
        // itemsView
        stackView.addArrangedSubview(itemsView)
        // textView
        stackView.addArrangedSubview(textView)
        textView.snp.makeConstraints { make in
            make.height.equalTo(61.0.wmc_autoHor)
        }
        // submitButton
        stackView.addArrangedSubview(submitButton)
        submitButton.snp.makeConstraints { make in
            make.height.equalTo(44.0.wmc_autoHor)
        }
        // tipLabel
        tipLabel.preferredMaxLayoutWidth = Wmc_screenWidth - hMargin * 2.0
        stackView.addArrangedSubview(tipLabel)
        
    }
    
    // MARK: Bind Action
    override func bindViewAction() {
        super.bindViewAction()
        // 点击关闭
        titleView.closeButton.rx.tap.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            if self.checkCanSubmit(toast: false) {
                self.showLeaveAlert()
                return
            }
            self.dismiss()
        }).disposed(by: rx.disposeBag)
        // 点击提交
        submitButton.rx.tap.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            if self.checkCanSubmit() {
                self.postFeedbackInfo()
            }
        }).disposed(by: rx.disposeBag)
    }

}

extension WmcCombinePhotoFeedbackAlertView {
    
    // MARK: Private
    private func reloadData() {
        for case let (index, itemView) as (Int, WmcCPFeedbackItemView) in itemsView.arrangedSubviews.enumerated() {
            let item = items[index]
            itemView.item = item
        }
    }
    
    /// 选中某个选项调用
    private func didSelected(itemView: WmcCPFeedbackItemView, item: WmcFeedbackItem) {
        if item.isChecked {
            item.isChecked = false
            selectedItem = nil
        } else {
            selectedItem?.isChecked = false
            item.isChecked = true
            selectedItem = item
        }
        let isOtherSelected = selectedItem?.isOther ?? false
        textView.isHidden = !isOtherSelected
        reloadData()
    }
    
    /// 加载反馈信息
    private static func loadFeedbackInfos(success: @escaping (([WmcFeedbackItem]) -> Void)) {
        WmcHudManager.loading()
        WmcFeedbackAPI.loadFeedbackConfigInfo(appId: appId, configId: configId).subscribe {
            items in
            WmcHudManager.dismiss()
            // "其他"选项
            let otherItem = items.first { $0.label == "其他" }
            otherItem?.isOther = true
            if items.isEmpty {
                WmcHudManager.defaultToast()
                return
            }
            success(items)
        } onError: { error in
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
        }.disposed(by: disposeBag)
    }
    
    /// 弹出弹窗
    private static func show(items: [WmcFeedbackItem]) {
        let alertView = WmcCombinePhotoFeedbackAlertView()
        alertView.items = items
        let sheetConfig = WmcPresentVC.Style.SheetConfig()
        sheetConfig.isAutoHeight = true
        var config = WmcPresentVC.Config.basicConfig(view: alertView, style: .sheet(sheetConfig)) { make in
            make.left.right.bottom.equalToSuperview()
        }
        config.isTouchMaskDismiss = false
        alertView.show(config: config)
    }
    /// 上传反馈信息
    private func postFeedbackInfo() {
        WmcHudManager.loading()
        var value: Int? = selectedItem?.value
        var content: String? = selectedItem?.label
        if let selectedItem = selectedItem,
           selectedItem.isOther {
            value = nil
            content = textView.text
        }
        WmcFeedbackAPI.postFeedbackRecord(appId: Self.appId, configId: Self.configId, classificationId: value, content: content).subscribe {
            [weak self] res in
            WmcHudManager.dismiss()
            guard let self = self else { return }
            WmcHudManager.toast("提交成功")
            self.dismiss()
        } onError: { error in
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }
    
    /// 检测是否可提交
    private func checkCanSubmit(toast: Bool = true) -> Bool {
        guard let selectedItem = selectedItem else {
            if toast {
                WmcHudManager.toast("未选择内容，无法提交")
            }
            return false
        }
        if selectedItem.isOther && (textView.text?.isEmpty ?? true) {
            if toast {
                WmcHudManager.toast("请输入提交内容")
            }
            return false
        }
        return true
    }
    
    /// 弹出挽留弹窗
    private func showLeaveAlert() {
        let alert = WmcAlertView()
        alert.title = "提示"
        alert.msg = "退出将不保存已选内容，确定退出？"
        alert.style = .custom(confirmTitle: "确定", cancelTitle: "取消")
        alert.confirmBlock = {
            [weak self] in
            guard let self = self else { return }
            self.dismiss()
        }
        alert.show()
    }
    
    /// 点击加群处理
    private func handleJoinGroup() {
        // 打开微信小程序
        WmcShareManager.followWechat()
    }
    
    // MARK: Public
    /// 弹出弹窗
    static func show() {
        loadFeedbackInfos { items in
            show(items: items)
        }
    }

}
